//
//  ZCMeTableViewController.m
//  BaiSi
//
//  Created by 张灿 on 16/4/24.
//  Copyright © 2016年 张灿. All rights reserved.
//

#import "ZCMeTableViewController.h"
#import "ZCSettingTableViewController.h"
#import "ZCCollectionViewCell.h"
#import <AFNetworking.h>
#import "ZCSquareItem.h"
#import <MJExtension/MJExtension.h>
#import <SafariServices/SafariServices.h>
#import "ZCWebViewController.h"

//间距
static CGFloat margin = 1;
//列
static NSInteger cols = 4;
//cell尺寸
#define wh (ZCScreenW - (cols - 1) * margin) / cols

static NSString * const ID = @"cell";

@interface ZCMeTableViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableArray *arrs;

@property (weak, nonatomic) UICollectionView *collectionV;

@end

@implementation ZCMeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavBar];
    
    //设置底部collectionView
    [self setupFootView];
    
    //加载数据
    [self loadData];
    
    //组,头部高度
    self.tableView.sectionHeaderHeight = 0;
    
    //设置额外滚动区域
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
    

}

- (void)setupNavBar
{
    //右
    UIBarButtonItem *itemSetting = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-setting-icon"] highlightImage:[UIImage imageNamed:@"mine-setting-icon-click"] Target:self action:@selector(setting)];
    UIBarButtonItem *itemNight = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"mine-moon-icon"] selImage:[UIImage imageNamed:@"mine-moon-icon-click"] Target:self action:@selector(night:)];
    
    self.navigationItem.rightBarButtonItems = @[itemSetting, itemNight];
    
    //中
    self.navigationItem.title = @"我的";
}

//设置按钮
- (void)setting
{
    ZCSettingTableViewController *settingVC = [[ZCSettingTableViewController alloc] init];
    //一定要在跳转之前隐藏底部导航栏
    settingVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:settingVC animated:YES];
}

//夜间模式
- (void)night:(UIButton *)btn
{
    NSLog(@"夜间模式");
    btn.selected = !btn.selected;
    
}

//设置底部collectionView视图
- (void)setupFootView
{
    //创建流水布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    //cell尺寸
    layout.itemSize = CGSizeMake(wh, wh);
    
    layout.minimumLineSpacing = margin;
    layout.minimumInteritemSpacing = margin;
    
    UICollectionView *collV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ZCScreenW, 400) collectionViewLayout:layout];
    
    //注册cell
    [collV registerNib:[UINib nibWithNibName:@"ZCCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
    collV.dataSource = self;
    collV.delegate = self;
    
    //背景色(分割线颜色)
    collV.backgroundColor = [UIColor clearColor];
    
    //添加
    self.tableView.tableFooterView = collV;
    
    self.collectionV = collV;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZCCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    ZCSquareItem *item = self.arrs[indexPath.row];
    
    cell.item = item;
    
    return cell;
    
}

#pragma mark - 加载数据
- (void)loadData
{
    //创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //配置请求体
    NSDictionary *dict = @{
                                  @"a" : @"square",
                                  @"c" : @"topic"
                                  };
    
    [manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.arrs = [ZCSquareItem mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"]];
        
        //补全空余的小格子
        [self resolveData];
        
        //设置collectionView不能滚动,即高度为内容高度
        //获取内容高度
        NSInteger maxrows = (self.arrs.count - 1) / 4 + 1;
        CGFloat h = maxrows * wh + maxrows * margin;
        self.collectionV.height = h;
        
        self.tableView.tableFooterView = self.collectionV;
        
        self.collectionV.backgroundColor = [UIColor lightGrayColor];
        //刷新
        [self.collectionV reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}

// 处理方块数据
- (void)resolveData
{
    // 3  1
    // 3 % 4 3 4 - 3
    
    NSInteger count = _arrs.count;
    
    NSInteger extre = count % cols;
    
    if (extre) {
        extre = cols - extre;
        for (int i = 0; i < extre; i++) {
            ZCSquareItem *item = [[ZCSquareItem alloc] init];
            [_arrs addObject:item];
        }
    }
    
}

#pragma mark - 代理
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //获取当前模型
    ZCSquareItem *item = self.arrs[indexPath.row];
    
    //判断是否是网页链接
    if (![item.url containsString:@"http"]) {
        return;
    }
    
//    //创建浏览器控制器
//    SFSafariViewController *vc = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:item.url]];
//    
//    //默认调用modal,但是会根据具体情况实际调用类似PUSH的方法
//    [self presentViewController:vc animated:YES completion:nil];
    //创建
    ZCWebViewController *webView = [[ZCWebViewController alloc] init];
    //传入url
    webView.url = [NSURL URLWithString:item.url];
    //push
    [self.navigationController pushViewController:webView animated:YES];
    
}

@end
